const fs = require('fs').promises;
const path = require('path');
const { setupLogger } = require('../utils/logger');
const config = require('../config/config');

// 导入各个数据源服务
const twitterService = require('./sources/twitterService');
const binanceService = require('./sources/binanceService');
const okxService = require('./sources/okxService');
const geckoTerminalService = require('./sources/geckoTerminalService');
const coinGeckoService = require('./sources/coinGeckoService');
const gmgnService = require('./sources/gmgnService');
const aveAiService = require('./sources/aveAiService');

// 导入数据存储服务
const storageService = require('./storageService');
const analysisService = require('./analysisService');

class DataService {
  constructor() {
    this.logger = setupLogger();
    this.isInitialized = false;
    this.dataCache = new Map();
    this.lastUpdate = null;
  }

  async initialize() {
    try {
      this.logger.info('初始化数据服务...');
      
      // 确保数据目录存在
      await this.ensureDirectories();
      
      // 初始化存储服务
      await storageService.initialize();
      
      // 加载现有数据
      await this.loadExistingData();
      
      this.isInitialized = true;
      this.logger.info('数据服务初始化完成');
    } catch (error) {
      this.logger.error('数据服务初始化失败:', error);
      throw error;
    }
  }

  async ensureDirectories() {
    const dirs = [
      config.storage.dataDir,
      './logs'
    ];
    
    for (const dir of dirs) {
      try {
        await fs.access(dir);
      } catch {
        await fs.mkdir(dir, { recursive: true });
        this.logger.info(`创建目录: ${dir}`);
      }
    }
  }

  async loadExistingData() {
    try {
      const jsonPath = path.join(config.storage.dataDir, config.storage.jsonFile);
      const data = await fs.readFile(jsonPath, 'utf8');
      const parsedData = JSON.parse(data);
      
      // 将数据加载到缓存中
      if (parsedData.tokens) {
        this.dataCache.set('tokens', parsedData.tokens);
      }
      if (parsedData.smartMoney) {
        this.dataCache.set('smartMoney', parsedData.smartMoney);
      }
      if (parsedData.marketData) {
        this.dataCache.set('marketData', parsedData.marketData);
      }
      
      this.lastUpdate = parsedData.lastUpdate || null;
      this.logger.info('已加载现有数据');
    } catch (error) {
      this.logger.info('未找到现有数据文件，将创建新的数据集');
    }
  }

  async refreshData() {
    if (!this.isInitialized) {
      throw new Error('数据服务未初始化');
    }

    this.logger.info('开始刷新数据...');
    const startTime = Date.now();
    
    try {
      // 并行获取各个数据源的数据
      const dataPromises = [];
      
      if (config.dataSources.twitter.enabled) {
        dataPromises.push(this.fetchTwitterData());
      }
      if (config.dataSources.binance.enabled) {
        dataPromises.push(this.fetchBinanceData());
      }
      if (config.dataSources.okx.enabled) {
        dataPromises.push(this.fetchOkxData());
      }
      if (config.dataSources.geckoTerminal.enabled) {
        dataPromises.push(this.fetchGeckoTerminalData());
      }
      if (config.dataSources.coinGecko.enabled) {
        dataPromises.push(this.fetchCoinGeckoData());
      }
      if (config.dataSources.gmgn.enabled) {
        dataPromises.push(this.fetchGmgnData());
      }
      if (config.dataSources.aveAi.enabled) {
        dataPromises.push(this.fetchAveAiData());
      }

      // 等待所有数据获取完成
      const results = await Promise.allSettled(dataPromises);
      
      // 处理结果
      const allData = [];
      results.forEach((result, index) => {
        if (result.status === 'fulfilled') {
          allData.push(...result.value);
        } else {
          this.logger.error(`数据源 ${index} 获取失败:`, result.reason);
        }
      });

      // 分析和处理数据
      const processedData = await analysisService.processData(allData);
      
      // 更新缓存
      this.updateCache(processedData);
      
      // 保存数据
      await storageService.saveData(processedData);
      
      this.lastUpdate = new Date().toISOString();
      const duration = Date.now() - startTime;
      
      this.logger.info(`数据刷新完成，耗时: ${duration}ms，获取数据: ${allData.length} 条`);
      
      return {
        success: true,
        dataCount: allData.length,
        duration,
        lastUpdate: this.lastUpdate
      };
    } catch (error) {
      this.logger.error('数据刷新失败:', error);
      throw error;
    }
  }

  updateCache(data) {
    if (data.tokens) {
      this.dataCache.set('tokens', data.tokens);
    }
    if (data.smartMoney) {
      this.dataCache.set('smartMoney', data.smartMoney);
    }
    if (data.marketData) {
      this.dataCache.set('marketData', data.marketData);
    }
  }

  async fetchTwitterData() {
    try {
      return await twitterService.fetchData();
    } catch (error) {
      this.logger.error('Twitter数据获取失败:', error);
      return [];
    }
  }

  async fetchBinanceData() {
    try {
      return await binanceService.fetchData();
    } catch (error) {
      this.logger.error('Binance数据获取失败:', error);
      return [];
    }
  }

  async fetchOkxData() {
    try {
      return await okxService.fetchData();
    } catch (error) {
      this.logger.error('OKX数据获取失败:', error);
      return [];
    }
  }

  async fetchGeckoTerminalData() {
    try {
      return await geckoTerminalService.fetchData();
    } catch (error) {
      this.logger.error('GeckoTerminal数据获取失败:', error);
      return [];
    }
  }

  async fetchCoinGeckoData() {
    try {
      return await coinGeckoService.fetchData();
    } catch (error) {
      this.logger.error('CoinGecko数据获取失败:', error);
      return [];
    }
  }

  async fetchGmgnData() {
    try {
      return await gmgnService.fetchData();
    } catch (error) {
      this.logger.error('GMGN数据获取失败:', error);
      return [];
    }
  }

  async fetchAveAiData() {
    try {
      return await aveAiService.fetchData();
    } catch (error) {
      this.logger.error('Ave.ai数据获取失败:', error);
      return [];
    }
  }

  async getData({ source, limit = 100, offset = 0, filter = {} }) {
    const allData = [];
    
    // 从缓存获取数据
    if (source) {
      const sourceData = this.dataCache.get(source) || [];
      allData.push(...sourceData);
    } else {
      // 获取所有数据
      for (const [key, value] of this.dataCache) {
        if (Array.isArray(value)) {
          allData.push(...value);
        }
      }
    }

    // 应用过滤器
    let filteredData = allData;
    if (filter.symbol) {
      filteredData = filteredData.filter(item => 
        item.symbol && item.symbol.toLowerCase().includes(filter.symbol.toLowerCase())
      );
    }
    if (filter.minPrice) {
      filteredData = filteredData.filter(item => 
        item.price && parseFloat(item.price) >= parseFloat(filter.minPrice)
      );
    }
    if (filter.maxPrice) {
      filteredData = filteredData.filter(item => 
        item.price && parseFloat(item.price) <= parseFloat(filter.maxPrice)
      );
    }

    // 分页
    const total = filteredData.length;
    const items = filteredData.slice(offset, offset + limit);
    
    return {
      items,
      total,
      hasMore: offset + limit < total
    };
  }

  async getTokens({ symbol, limit = 50 }) {
    const tokens = this.dataCache.get('tokens') || [];
    
    let filteredTokens = tokens;
    if (symbol) {
      filteredTokens = tokens.filter(token => 
        token.symbol && token.symbol.toLowerCase().includes(symbol.toLowerCase())
      );
    }
    
    return filteredTokens.slice(0, limit);
  }

  async getSmartMoney({ limit = 20 }) {
    const smartMoney = this.dataCache.get('smartMoney') || [];
    return smartMoney.slice(0, limit);
  }

  getLastUpdate() {
    return this.lastUpdate;
  }

  getCacheStats() {
    const stats = {};
    for (const [key, value] of this.dataCache) {
      if (Array.isArray(value)) {
        stats[key] = value.length;
      } else {
        stats[key] = typeof value;
      }
    }
    return stats;
  }
}

module.exports = new DataService();

